package com.idp.web.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.idp.common.enums.DataStatusEnum;
import com.idp.common.model.LoginInfo;
import com.idp.system.entity.SysUserEntity;
import com.idp.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * web用户验证处理
 * @author king
 */
@Service("SysUserDetailsServiceImpl")
public class SysUserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(SysUserDetailsServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LambdaQueryWrapper<SysUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserEntity::getDelFlag, DataStatusEnum.NORMAL.code);
        queryWrapper.eq(SysUserEntity::getUname, username);
        SysUserEntity sysUser = sysUserMapper.selectOne(queryWrapper);

        if (sysUser == null) {
            log.info("系统用户：{} 不存在.", username);
            throw new UsernameNotFoundException("用户不存在");
        }

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setId(sysUser.getId());
        loginInfo.setAccount(sysUser.getUname());
        loginInfo.setPwd(sysUser.getPwd());
        loginInfo.setPhone(sysUser.getPhone());
        loginInfo.setName(sysUser.getFullName());

        return loginInfo;
    }

}
